<?php
namespace lightblog\engine;

use lightblog\engine\model;

interface dbDriver {
    public function query($sql);
    public function connect($host, $name, $pwd, $db, $port);
}


class db extends model implements dbDriver {
    public static $dbh;

    function __construct() {
        $dbcfg = \lightblog::$app->config['db'];
        $this->connect($dbcfg['host'], $dbcfg['user'], $dbcfg['pwd'], $dbcfg['name'], $dbcfg['port']);
    }

    function connect($host, $uname, $pwd, $dbname, $port = 3306) {
        if (!self::$dbh) {
            self::$dbh = @mysql_connect("$host:$port", $uname, $pwd);
            mysql_select_db($dbname);
            mysql_query('SET NAMES utf8');
        }
    }

    function query($sql) {
        $res = mysql_query($sql, self::$dbh);

        if (!$res) {
            $error = mysql_error();
            $str = "Query failed... SQL: $sql\nError: $error\n";
            echo nl2br($str);
            return false;
        }

        return $res;
    }

    function getLastInsertId() {
        return mysql_insert_id();
    }

    function insert($sql) {
        $this->query($sql);

        return $this->getLastInsertId();
    }

    function update($sql) {
    }

    function delete($sql) {
    }

    /**
     * 执行选取操作
     *
     * @param string $sql 要执行的sql语句
     * @param integer $raw 是不是优化结果
     *
     * @return mixed 返回结果
     */
    function select($sql, $raw = true) {
        $res = array();
        $rows = $this->query($sql);
        $this->num_rows = mysql_num_rows($rows);
        $this->num_fields = mysql_num_fields($rows);

        // 结果集为单行, 且要求优化
        if (!$raw && $this->num_rows == 1) {
            $row = mysql_fetch_assoc($rows);

            // 结果集还是单列, 返回标量值
            if ($this->num_fields == 1) {
                return current($row);
            }

            // 返回这一行
            return $row;
        }

        while ($row = mysql_fetch_assoc($rows)) {
            $res[] = $row;
        }

        return $res;
    }
}
